package com.ruge.tool.autosign.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruge.tool.json.JsonTool;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.StringJoiner;

@Slf4j
public class HttpURLConnectionUtils {

    /**
     * 基于HttpURLConnection对象封装的get请求
     */
    public static String get(String url, Map<String, String> requestParam, Map<String, String> headers) throws IOException {
        String requestPath = url;
        StringJoiner stringJoiner = null;
        if (requestParam != null && !requestParam.isEmpty()) {
            stringJoiner = new StringJoiner("&", "?", "");
            for (Map.Entry<String, String> header : headers.entrySet()) {
                String key = header.getKey();
                String value = header.getValue().toString();
                stringJoiner.add(URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"));
            }
        }
        if (!(stringJoiner == null)) {
            requestPath = requestPath + stringJoiner;
        }
        URL requestUrl = new URL(requestPath);
        HttpURLConnection httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setInstanceFollowRedirects(false);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        if (headers != null && !(headers.isEmpty())) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                String key = header.getKey();
                String value = header.getValue().toString();
                httpURLConnection.setRequestProperty(key, value);
            }
        }
        String body = HttpUtil.createGet(requestPath).addHeaders(headers).execute().body();
        String response = getResponse(httpURLConnection);
        log.info("\n本次get请求：\nURL is {}\n请求头：{}\n返回值：{}", requestPath, (headers == null) ? null : JsonTool.getObjToJson(headers), response);
        httpURLConnection.disconnect();
        return response;
    }

    /**
     * 基于HttpURLConnection对象封装的post请求
     */
    public static String post(String url, Map<String, String> requestParam, Map<String, String> headers, JSONObject requestBody) throws IOException {
        String requestPath = url;
        StringJoiner stringJoiner = null;
        if (requestParam != null && !requestParam.isEmpty()) {
            stringJoiner = new StringJoiner("&", "?", "");
            for (Map.Entry<String, String> header : headers.entrySet()) {
                String key = header.getKey();
                String value = header.getValue().toString();
                stringJoiner.add(URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"));
            }
        }
        if (!(stringJoiner == null)) {
            requestPath = requestPath + stringJoiner;
        }
        URL requestUrl = new URL(requestPath);
        HttpURLConnection httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setInstanceFollowRedirects(false);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        if (requestBody != null && !("".equals(requestBody.toString()))) {
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(requestBody.toString().getBytes().length));
        }
        if (headers != null && !(headers.isEmpty())) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                String key = header.getKey();
                String value = header.getValue().toString();
                httpURLConnection.setRequestProperty(key, value);
            }
        }
        if (requestBody != null && !("".equals(requestBody.toString()))) {
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(requestBody.toString().getBytes());
            outputStream.flush();
            outputStream.close();
        }
        String response = getResponse(httpURLConnection);
        log.info("\n本次post请求：\nURL is {}\n请求头：{}\n请求体：{}\n返回值：{}", requestPath, (headers == null) ? null : JsonTool.getObjToJson(headers), (requestBody == null) ? null : JsonTool.getObjToJson(requestBody), response);

        httpURLConnection.disconnect();
        return response;
    }

    /**
     * 获取HttpURLConnection对象的响应信息方法
     */
    private static String getResponse(HttpURLConnection httpURLConnection) {
        try {
            int statusCode = httpURLConnection.getResponseCode();
            InputStream inputStream = statusCode == 200 ? httpURLConnection.getInputStream() : httpURLConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
//            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.ISO_8859_1));
//            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GB2312"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            httpURLConnection.disconnect();
        }
    }
}